package aliyun

import (
	"bytes"
	"errors"
	"strings"

	"gitee.com/bjf-fhe/apicat/notify"
	aliyun_notifier "gitee.com/bjf-fhe/apicat/notify/aliyun"
	"gitee.com/bjf-fhe/apicat/platform"
	"gitee.com/bjf-fhe/apicat/source"
	aliyun_log_source "gitee.com/bjf-fhe/apicat/source/aliyun"
	aliyun_csv_source "gitee.com/bjf-fhe/apicat/source/csv"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	"github.com/extrame/tail"
	"github.com/spf13/pflag"
)

type Config struct {
	Dest            string
	DestV6          string
	AccessKeyId     string
	AccessKeySecret string
	regionId        string
	inited          bool
}

func (h *Config) AddFlags(set *pflag.FlagSet) {
	set.StringVar(&h.AccessKeyId, "accesskey-id", "", "阿里云的AccessKeyId")
	set.StringVar(&h.AccessKeySecret, "accesskey-secret", "", "阿里云的AccessKeySecret")
	set.StringVar(&h.Dest, "dest", "", "写入IPv4规则的目标规则组")
	set.StringVar(&h.DestV6, "dest-v6", "", "写入IPv6规则的目标规则组")
	set.StringVar(&h.regionId, "region-id", "", "需要对接的负载均衡所在Aliyun Region")
}

func (h *Config) GetNotifier(ncfg *notify.Config) (platform.Notifier, error) {
	var notifier aliyun_notifier.Handler

	err := notifier.Init(ncfg, &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: &h.AccessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: &h.AccessKeySecret,
		RegionId:        &h.regionId,
	}, h.Dest, h.DestV6)
	return &notifier, err
}

func (h *Config) GetSource(fh platform.RootConfiger, tailMode bool) (source.Reader, error) {

	if fh.IsLocalFile() {
		if tailMode {
			//csv mode, csv不支持tail模式
			if strings.HasSuffix(fh.GetFileName(), ".gz") {
				return nil, errors.New("CSV压缩文件读取不支持Tail模式")
			}

			var buf = &bytes.Buffer{}

			var t *tail.Tail

			t, err := tail.TailFile(fh.GetFileName(), tail.Config{Follow: true, Poll: true})

			if err == nil {
				go func() {
					for line := range t.Lines {
						buf.Write([]byte(line.Text + "\n"))
					}
				}()
				return aliyun_csv_source.NewReader(buf, true)
			} else {
				return nil, err
			}

		} else {
			f, err := fh.OpenFile()
			if err == nil {
				return aliyun_csv_source.NewReader(f, false)
			}
			return nil, err
		}
	} else {
		parts := strings.Split(fh.GetFileName(), "/")
		if len(parts) != 2 {
			return nil, errors.New("传入线上日志点格式错误，请传入'project'/'logstore'格式，例如oss-log-xxxxxx-cn-beijing/oss-log-store")
		}
		return aliyun_log_source.NewReader(fh.GetFileName(), &openapi.Config{
			// 必填，您的 AccessKey ID
			AccessKeyId: &h.AccessKeyId,
			// 必填，您的 AccessKey Secret
			AccessKeySecret: &h.AccessKeySecret,
			RegionId:        &h.regionId,
		}, parts[0], parts[1])
	}
}

func (h *Config) Check() error {
	if h.AccessKeyId == "" {
		return errors.New("AccessKeyId没有设置，请使用--aliyun-accesskey-id配置该参数")
	}

	if h.AccessKeySecret == "" {
		return errors.New("AccessKeySecret没有设置，请使用--aliyun-accesskey-secret配置该参数")
	}

	if h.regionId == "" {
		return errors.New("Region Id 没有设置，请使用--aliyun-region-id配置该参数")
	}

	return nil
}

func init() {
	platform.Register("aliyun", &Config{})
}
